<template>
  <div>
    <el-form :model="form" ref="deptForm" :rules="rules" label-width="120px">
      <el-form-item label="部门名称" prop="name">
        <el-input
          v-model="form.name"
          style="width: 80%"
          placeholder="1-50个字符"
        />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input
          v-model="form.code"
          style="width: 80%"
          placeholder="1-50个字符"
        />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select
          v-model="form.manager"
          style="width: 80%"
          placeholder="请选择"
        >
          <el-option
            v-for="item in employees"
            :key="item.id"
            :value="item.username"
            :label="item.username"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input
          v-model="form.introduce"
          style="width: 80%"
          placeholder="1-300个字符"
          type="textarea"
          :rows="3"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="small" @click="hSubmit">确定</el-button>
        <el-button size="small" @click="hCancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { getSimple } from "@/api/employees";
import {
  addDepartments,
  getDepartDetail,
  UpDepartDetail,
} from "@/api/departments";
export default {
  name: "deptDialog",
  props: {
    cruId: {
      type: String,
      required: true,
    },
    isEdit: {
      type: Boolean,
      required: true,
    },
    originList: {
      type: Array,
      required: true,
    },
  },
  data() {
    //部门编码效验规则
    const validCodePass = (rule, value, callback) => {
      let existCodeList = this.originList.map((item) => item.code);
      //如果是编辑部门。筛选出当前部门的编号，在map得到新的部门
      if (this.isEdit) {
        existCodeList = this.originList
          .filter((item) => item.id !== this.cruId)
          .map((item) => item.code);
      }
      existCodeList.includes(value)
        ? callback(new Error("部门编码:" + value + "已存在"))
        : callback();
    };
    //部门名称效验规则
    const validNamePass = (rule, value, callback) => {
      // 先找到父级同部门的子部门，在通过map返回当前部门所有的名称
      let existNameList = this.originList
        .filter((item) => item.pid === this.cruId)
        .map((item) => item.name);
      if (this.isEdit) {
        // 1.找到当前编辑部门的对象，find==>第一个找到的对象
        const detp = this.originList.find((item) => item.id === this.cruId);
        // 2.获取当前编辑对象的pid
        const pid = detp.pid;
        // 3.构建已存储的数据列表，找到所有的兄弟（包括自己） 存在列表=兄弟-自己
        existNameList = this.originList
          .filter((item) => item.pid === pid && item.id !== this.cruId)
          .map((item) => item.name);
      }

      existNameList.includes(value)
        ? callback(new Error("部门名称:" + value + "已存在"))
        : callback();
    };
    return {
      form: {
        name: "",
        code: "",
        manager: "",
        introduce: "",
      },
      employees: [],
      rules: {
        name: [
          { required: true, message: "部门名称不能为空", trigger: "blur" },
          {
            min: 1,
            max: 50,
            message: "部门名称要求1-50个字符",
            trigger: "blur",
          },
          { validator: validNamePass, trigger: "blur" },
        ],
        code: [
          { required: true, message: "部门编码不能为空", trigger: "blur" },
          {
            min: 1,
            max: 50,
            message: "部门编码要求1-50个字符",
            trigger: "blur",
          },
          { validator: validCodePass, trigger: "blur" },
        ],
        manager: [
          { required: true, message: "部门负责人不能为空", trigger: "blur" },
        ],
        introduce: [
          { required: true, message: "部门介绍不能为空", trigger: "blur" },
          {
            min: 1,
            max: 300,
            message: "部门介绍要求1-300个字符",
            trigger: "blur",
          },
        ],
      },
    };
  },
  created() {
    this.loadEmployee();
    //获取部门详情
    this.loadDetail();
  },
  methods: {
    //发送员工下拉列表
    async loadEmployee() {
      try {
        const res = await getSimple();
        this.employees = res.data;
      } catch (error) {}
    },
    //新增部门
    async doAdd() {
      const res = await addDepartments({ ...this.form, pid: this.cruId });
      this.$emit("success");
    },
    //根据id获取部门详情
    async loadDetail() {
      try {
        if (this.isEdit) {
          const res = await getDepartDetail(this.cruId);
          this.form = res.data;
        }
      } catch {}
    },
    //编辑部门
    async doEdit() {
      try {
        const res = await UpDepartDetail(this.form);
        this.$emit("success");
      } catch (error) {}
    },
    //确定
    hSubmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.isEdit ? this.doEdit() : this.doAdd();
        }
      });
    },
    // 取消
    hCancel() {
      this.$emit("close");
    },
  },
};
</script>

<style lang="scss" scoped>
</style>